package walletadminlogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryGameOrderFlowListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryGameOrderFlowListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryGameOrderFlowListLogic {
	return &QueryGameOrderFlowListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理后台查询游戏下单流水
func (l *QueryGameOrderFlowListLogic) QueryGameOrderFlowList(in *pb.QueryGameOrderFlowListReq) (*pb.QueryGameOrderFlowListResp, error) {
	defer utils.RecoverPanic()

	var start, end *time.Time
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
		start = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
		end = &t
	}
	var err error
	var list []*wallet.UserGameOrderFlow
	list, err = l.svcCtx.UserGameOrderFlowModel.Find(l.ctx, in.GameId, in.Uid, in.ProviderId, in.MoneyType, start, end, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.QueryGameOrderFlowListResp
	resp.List = make([]*pb.GameOrderFlow, 0)
	if len(list) <= 0 {
		return &resp, nil
	}
	if in.PageNo <= 1 {
		resp.Total, err = l.svcCtx.UserGameOrderFlowModel.CountOrderCount(l.ctx, in.GameId, in.Uid, in.ProviderId, in.MoneyType, 0, start, end)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		var vl pb.GameOrderFlow
		vl.FlowNo = list[i].FlowNo
		vl.Uid = list[i].Uid
		vl.GameId = list[i].GameId
		vl.ProviderId = list[i].ProviderId
		vl.MoneyType = list[i].MoneyType
		vl.MoneyAmount = decimal.NewFromInt(list[i].MoneyAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
		vl.ReturnAmount = decimal.NewFromInt(list[i].ReturnAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
		vl.State = list[i].State
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		vl.UpdateTime = list[i].UpdateTime.Format(dbkey.DateTimeCNFormat)
		vl.ExFlow = list[i].ExternalFlowNo
		vl.OrderTime = list[i].OrderTime.Format(dbkey.DateTimeCNFormat)
		resp.List = append(resp.List, &vl)
	}
	return &resp, nil
}
